package com.atguigu.dao.impl;
import com.atguigu.utils.jdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 14587
 * @date 2020/10/19 15:52
 */
public abstract class BaseDao {
    private QueryRunner queryRunner = new QueryRunner();
    /**
    * @author VegetDog
    * @Description 用于增加修改删除
    * @date 2020-10-19 16:07
     * @param sql
     * @param args
     * @return int 返回修改的行数
     */
    public int update(String sql,Object...args){
    Connection conn = jdbcUtils.getConnection();
    try {
        return queryRunner.update(conn,sql,args);
    } catch (SQLException throwables) {
        throwables.printStackTrace();
        throw new RuntimeException();
    }
    }

    public <T> T queryForOne(Class<T> type,String sql,Object... args){
    Connection conn=jdbcUtils.getConnection();
    try {
        return queryRunner.query(conn, sql, new BeanHandler<T>(type),args);
    } catch (SQLException throwables) {
        throwables.printStackTrace();
        throw new RuntimeException();
    }
    }
    /**
     * @author VegetDog
     * @Description 查询多个对象
     * @date 2020-10-19 16:23
     * @param type 查询的类型
 * @param sql   查询语句
 * @param args
     * @return java.util.List<T>
     */
    public <T>List<T> queryForList(Class<T> type,String sql,Object... args){
        Connection conn=jdbcUtils.getConnection();
        List<T> queryList = null;
        try {
            return queryRunner.query(conn, sql, new BeanListHandler<T>(type), args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException();
        }
    }
    /**
     * @author VegetDog
     * @Description 返回单个值
     * @date 2020-10-19 16:27
     * @param sql
 * @param args
     * @return java.lang.Object
     */
    public Object queryForSingleValue(String sql,Object...args){
        Connection conn=jdbcUtils.getConnection();
        try {
            return queryRunner.query(conn,sql,new ScalarHandler(),args);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
            throw new RuntimeException();
        }
    }
}
